﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using SpringWaterDataAccess;

namespace test
{
	/// <summary>
	/// Summary description for forums.
	/// </summary>
	public partial class forums : System.Web.UI.Page
	{
		private const int DisplayLinks = 5;

		// parameters to add links to the the header and footer
		int TotalTopics = 0;
		int TopicsPerPage = 0;
		string ForumID;
		string ForumName;
		string CategoryID;
		string CategoryName;
		string currPage;
		protected System.Web.UI.WebControls.HyperLink linkHomePage;
		protected System.Web.UI.WebControls.Label lblLevel1;
		protected System.Web.UI.WebControls.DataGrid DataGridForum;
		protected System.Web.UI.WebControls.HyperLink linkCategory;
		protected System.Web.UI.WebControls.Label lblLevel3;
		protected System.Web.UI.WebControls.HyperLink linkForum;
		protected System.Web.UI.WebControls.Label lblLevel2;
		protected System.Web.UI.WebControls.HyperLink linkForums;
		protected System.Web.UI.WebControls.Repeater Repeater1; 
		string startTopicID;

	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Retrieve the parameters
			ForumID = Request.QueryString["ForumID"];
			ForumName = Request.QueryString["ForumName"];
			CategoryID = Request.QueryString["CategoryID"];
			CategoryName = Request.QueryString["CategoryName"];
			currPage= Request.QueryString["CurrPage"];
			startTopicID = Request.QueryString["StartID"];

			if (ForumID == null || ForumID == "") 
			{
				ForumID = "11";
            }

			if (CategoryID == null || CategoryID == "") 
			{
				CategoryID = "33";
			}

			HttpCookie emailCookie = Request.Cookies["Email"];

			if (emailCookie != null) 
			{
				 
				if (CategoryID != null && ForumID != null) 
				{
					newArticleButton.Text = "发表新文章";
				} 
			} 
			else  
			{
				 			
				newArticleButton.Text = "请先注册或登录,发表文章";
				//newArticleButton.Attributes.Add("style", "text-decoration:none");
			}

			// populate the navigation pane for forum or category
			ForumDataAccess da = new ForumDataAccess();

			int total;
			DataSet topDS = da.getPosts(0,0,0,0,1,0,out total,"bbs","Top",
				Convert.ToUInt16(CategoryID),"CreateDate");

			DataList1.DataSource = topDS;
			DataList1.DataBind();
			 
			DataSet bbsDS = 
				da.GetForumCategoryPosts(ForumID,CategoryID,currPage,startTopicID,
				out TotalTopics, out TopicsPerPage);

			//bbsDS.Tables[0].DefaultView.RowFilter = "Type = bbs";
			DataGridTopic.DataSource = bbsDS.Tables[0].DefaultView;

			DataGridTopic.DataBind();		
		}

		public string getForumSeperator()
		{
			if (ForumName != null) 
				return "->";
			else 
				return "???";

		}

		public string getCategorySeperator()
		{
			if (CategoryName != null) 
				return "->";
			else 
				return "???";

		}

		public void DataGridTopic_OnItemDataBound(Object sender, DataGridItemEventArgs e)
		{
			// this is needed to overwrite the content bounded
			if (e.Item.ItemType == ListItemType.Item || 
				e.Item.ItemType == ListItemType.AlternatingItem)
			{
				DataRowView currView = (DataRowView)e.Item.DataItem;
				
				int level = int.Parse(currView.Row.ItemArray[2].ToString());	// level
				StringBuilder url = new StringBuilder();
				
				if (level ==1)
					url.Append("");
				
				for (int i=1;i<level;i++)
					url.Append("&nbsp;&nbsp;");
				url.Append("<font size =3> <b>.</b> </font>");

				// display detail link if Size is not zero
				int size = int.Parse(currView.Row.ItemArray[4].ToString());
				//if (size!=0)
				url.Append(string.Format("<a href=forumPostDetail.aspx?PostID={0}&CategoryID={1}&ForumID={2}&ForumName={3}&CategoryName={4}&CurrPage={5} style=text-decoration:none>", 
					currView.Row.ItemArray[0].ToString(), 
					currView.Row.ItemArray[1].ToString(),
					ForumID,
					ForumName,
					CategoryName,
					currPage));

				if (level ==1) 
				{
					url.Append("<font color=blue>");
				} 
				else 
				{
					url.Append("<font color=green>");
				}

				url.Append(currView.Row.ItemArray[3]);	// subject
				url.Append("</font>");
				//if (size!=0)
				url.Append("</a>");

				if (level ==1) 
				{
					url.Append("-<font color=blue size=2>");
				} 
				else 
				{
					url.Append("-<font color=green size=2>");
				}

				url.Append(currView.Row.ItemArray[6].ToString() );
				DateTime dt = System.Convert.ToDateTime(currView.Row.ItemArray[5].ToString());
				url.Append("-" + dt);
				url.Append(" (" + currView.Row.ItemArray[7].ToString() + " reads) (" + currView.Row.ItemArray[4].ToString()+ " bytes)");
				
				url.Append("</font>");

				url.Append("</li>");
				//for (int i=1;i<level;i++)
				//	url.Append("</ul>");
				e.Item.Cells[0].Text = url.ToString();
			}
			else if (e.Item.ItemType == ListItemType.Header || e.Item.ItemType == ListItemType.Footer)
			{
				if (!(this.TotalTopics == 0 && e.Item.ItemType == ListItemType.Footer))
				{
					int curr = 0;
					if (currPage != null) curr = int.Parse(currPage);
					int totalPages = (TotalTopics-1)/TopicsPerPage + 1;
					int startPage = (curr-DisplayLinks<0)?0:curr-DisplayLinks;
					int endpages = (curr+DisplayLinks>totalPages)? totalPages:curr+DisplayLinks;

					// build the url
					StringBuilder sb = new StringBuilder("forums.aspx");
					if (ForumID != null)
					{
						sb.Append(string.Format("?ForumID={0}&ForumName={1}",ForumID, ForumName));
						if (CategoryID != null)
						{
							sb.Append(string.Format("&CategoryID={0}&CategoryName={1}",CategoryID, CategoryName));
						}
						sb.Append("&");
					}
					else
						sb.Append("?");

					// constant
					Literal l = new Literal();
					l.Text = "<font size=2>页:";
					
					e.Item.Cells[0].Controls.Add(l);
					

					// seperator
					Literal preSpace = new Literal();
					preSpace.Text = " ";
					// display the link to previous page
					HyperLink prevLink = new HyperLink();
					prevLink.Text = "[";
					if (startPage<curr)
						prevLink.NavigateUrl = string.Format("{0}CurrPage={1}", sb.ToString(),curr-1);
					e.Item.Cells[0].Controls.Add(prevLink);
					e.Item.Cells[0].Controls.Add(preSpace);

					// display 5 pages up to curr pages
					for (int i=startPage;i<curr;i++)
					{
						HyperLink link = new HyperLink();
						link.Text = i.ToString();
						link.NavigateUrl = string.Format("{0}CurrPage={1}",  sb.ToString(),i);
						e.Item.Cells[0].Controls.Add(link);
						Literal space = new Literal();
						space.Text = " ";
						e.Item.Cells[0].Controls.Add(space);
					}

					// display current page
					HyperLink currLink = new HyperLink();
					currLink.Text = curr.ToString();
					e.Item.Cells[0].Controls.Add(currLink);
					Literal currSpace = new Literal();
					currSpace.Text = " ";
					e.Item.Cells[0].Controls.Add(currSpace);

					// display 5 pages after curr page
					for (int i=curr+1;i<endpages;i++)
					{
						HyperLink link = new HyperLink();
						link.Text = i.ToString();
						link.NavigateUrl = string.Format("{0}CurrPage={1}",  sb.ToString(),i);
						e.Item.Cells[0].Controls.Add(link);
						Literal space = new Literal();
						space.Text = " ";
						e.Item.Cells[0].Controls.Add(space);
					}

					// display next page
					HyperLink nextLink = new HyperLink();
					nextLink.Text = "]</font>";
					if (curr+1<endpages)
						nextLink.NavigateUrl = string.Format("{0}CurrPage={1}", sb.ToString(),curr+1);
					e.Item.Cells[0].Controls.Add(nextLink);
					e.Item.Cells[0].HorizontalAlign = HorizontalAlign.Right;
				
				}
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		private void DataGridTopic_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		
		}

		private void DataGridForum_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		
		}

		protected void newArticleButton_Click(object sender, System.EventArgs e)
		{
		}

        protected void newArticleButton_Click1(object sender, EventArgs e)
        {

            if (Request.Cookies["Email"] == null)
            {
                Response.Redirect("index.aspx?message=请您先注册/登录，再发表文章 !");
            }
            else if (CategoryID != null)
            {
                Response.Redirect("forumPostReply.aspx?categoryID=" + CategoryID
                    + "&categoryName=" + CategoryName
                    + "&ForumID=" + ForumID
                    + "&ForumName=" + ForumName);
            }
        }
	}
}
